package com.li.list;

public class 删除倒数第k个节点 {
	public static void main(String[] args) {
		Node head = new Node();
		Node node1 = new Node(1);
		Node node2 = new Node(2);
		Node node3 = new Node(3);
		Node node4 = new Node(4);
		Node node5 = new Node(5);
		Node node6 = new Node(6);

		head.next = node1;
		node1.next = node2;
		node2.next = node3;
		node3.next = node4;
		node4.next = node5;
		node5.next = node6;
		
		printList(head);
		deleteKthNode(head,3);
		printList(head);
	}
	
	/**
	 * 删除倒数第k个节点
	 * @param head
	 * @param k
	 * @return
	 */
	public static Node deleteKthNode(Node head, int k){
		if(head == null || head.next == null){
			return head;
		}
		Node node1 = head;
		Node node2 = head;
		for(int i = 0;i <= k;i++){
			if(node1 == null){
				return null;
			}
			node1 = node1.next;
		}
		while(node1!=null){
			node1 = node1.next;
			node2 = node2.next;
		}
		node2.next = node2.next.next;
		return head;
	}
	
	/**
	 * 打印链表
	 * @param head
	 */
	public static void printList(Node head){
		while((head = head.next)!=null){
			System.out.print(head.value+" ");
		}
		System.out.println();
	}
}
